<?php


namespace app\unify\model;


use app\unify\model\User as UserModel;
use thans\jwt\facade\JWTAuth;
use think\annotation\model\relation\BelongsTo;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\db\Query;
use think\facade\Log;
use think\model\concern\SoftDelete;


#[BelongsTo('userRole', UserRole::class, 'role_id', 'id')]
class User extends Base
{

    private static $id, $current;

    protected $readonly = ['creator_id', 'id', 'gmt_create', 'gmt_modified'];

    use SoftDelete;

    //超级管理员ID
    const ID_ADMIN = 1;
    const USERNAME_ADMIN = 'admin';

    public $autoWriteTimestamp = true;

    const STATUS_DISABLE = 0;
    const STATUS_ENABLE = 1;
    const STATUS_LIST = [
        self::STATUS_ENABLE => '启用',
        self::STATUS_DISABLE => '禁用'
    ];

    /**
     * @Notes 当前登录用户
     * @Author EdwardCho
     * @Date 2023/11/30
     * @Time 12:48
     * @Interface current
     */
    public static function current()
    {
        if (!self::id()) {
            return null;
        }

        if (empty(self::$current)) {
            self::$current = UserModel::field('id,nick,username,status,email,mobile,password,platform')
                ->withSearch(['id'], [
                    'id' => self::id()
                ])->findOrEmpty();
        }

        return self::$current;
    }

    /**
     * @Notes 是否为超级管理员
     * @Author EdwardCho
     * @Date 2024/1/4
     * @Time 12:56
     * @Interface isAdmin
     */
    public function isAdmin(){
        return $this->getData('username') == self::USERNAME_ADMIN;
    }

    public static function logout()
    {
        try {
            JWTAuth::invalidate(JWTAuth::token());
        } catch (\Exception $e) {

        }
    }

    public static function getHashPassword(string $password)
    {
        return password_hash(md5($password), PASSWORD_DEFAULT);
    }

    public static function verifyPassword($password, $hashPassword)
    {
        return password_verify(md5($password), $hashPassword);
    }

    public static function getToken($user)
    {
        return JWTAuth::builder([
            'uid' => $user['id']
        ]);
    }

    public function searchIdAttr(Query $q, $value, $data): void
    {
        $q->where('id', '=', $value);
    }


    /**
     * @Notes 获取当前用户标识
     * @Author EdwardCho
     * @Date 2022/8/16
     * @Time 13:58
     * @Interface id
     * @return mixed
     */
    public static function id()
    {
        if (!isset(self::$id)) {
            try {
                $info = JWTAuth::auth();
            } catch (\Exception $e) {
                $info = [];
            }

            Log::debug(json_encode($info, JSON_UNESCAPED_UNICODE));

            self::$id = !empty($info) ? $info['uid'] : 0;
        }

        return self::$id;
    }

    public function roles()
    {
        return $this->belongsToMany(
            Role::class,
            UserRole::class,
            'role_id',
            'user_id'
        );
    }

    public function userRoles(){
        return $this->hasMany(UserRole::class, 'user_id', 'id');
    }

    public function roleIds()
    {
        return $this->hasMany(UserRole::class, 'user_id', 'id');
    }


    public function getStatusNameAttr($value, $data)
    {
        return self::STATUS_LIST[$data['status']] ?? "";
    }

}
